<?php
/**
 * Created by PhpStorm.
 * User: qishengqiang
 * Date: 2022-09-30
 * Time: 12:51
 */

namespace app\services;


use app\models\Configs;
use app\models\GdzyzActivities;
use app\models\GdzyzConfig;
use app\models\WeikeyunOrders;
use app\models\WeikeyunOrdertype;
use GuzzleHttp\Client;

class GdzyzService extends ServiceBase
{
    protected $config = [];

    protected $gdzyz_url = '';

    protected $gdzyz_token = '';

    public function __construct()
    {
        $this->config = (new ConfigService())->getAll();
        $this->gdzyz_url = (new ConfigService())->getDetail('gdzyz_url');
        $this->gdzyz_token = (new ConfigService())->getDetail('gdzyz_token');
    }

    /**
     * @param $params
     * @param $page
     * @param $pagesize
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     */
    public function getLists($params, $page, $pagesize)
    {
        $activities = GdzyzActivities::lists($params, $page, $pagesize);

        return $activities;
    }

    /**
     * @throws \Exception
     */
    public function getActivityLists()
    {
        try {
            $activities = [];
            $page = 1;
            $pagesize = 100;
            do {
                $url = $this->gdzyz_url.'/api/mission/manage/findMissionList.do';
                //print_r($url);die;
                $client = new Client();

                $params = [
                    'headers' => $this->_get_header(),
                    'query' => [
                        'type' => 1,
                        'selectedLabelIdList' => '',
                        'missionId' => '',
                        'subject' => '',
                        'contactName' => '',
                        'contactPhone' => '',
                        'missionType' => '',
                        'serviceTimeType' => '',
                        'zzName' => '',
                        'districtId' => '',
                        'beginDateInput' => '',
                        'endDateInput' => '',
                        'pageIndex' => $page,
                        'pageSize' => $pagesize
                    ]
                ];

                $res = $client->get($url, $params);

                $data = json_decode($res->getBody()->__toString());

                if ($data->code == 1) {
                    $activities = $data->records;
                    if (count($activities)) {
                        foreach ($activities as $val) {
                            $activity = GdzyzActivities::where(['missionId' => $val->missionId])->find();

                            if (!$activity) {
                                $activity = new GdzyzActivities();
                                $activity->missionId = $val->missionId;
                                $activity->signStartTime = date('Y-m-d 00:00:00');
                            }

                            $activity->districtName = $val->districtName;
                            $activity->subject = $val->subject;
                            $activity->summary = $val->summary;
                            $activity->remark = $val->remark;
                            $activity->missionTypeName = $val->missionTypeName;
                            $activity->missionImg = 'http://image.izyz.org/obs-izy'.$val->missionImgB;
                            $activity->stateName = $val->stateName;
                            $activity->selectedLabelIdListName = $val->selectedLabelIdListName;
                            $activity->startDate = $val->startDate;
                            $activity->endDate = $val->endDate;
                            $activity->applyDeadline = $val->applyDeadline;
                            $activity->contactName = $val->contactName;
                            $activity->contactPhone = $val->contactPhone;
                            $activity->createdAt = $val->createDatetime;
                            $activity->save();
                        }
                    }
                }

                $page++;

            } while(count($activities));

        } catch (\Exception $e) {
            throw new \Exception($e->getMessage(), 500);
        }
    }

    public function refreshCode(GdzyzActivities $activity)
    {
        $code1 = 0;
        $code2 = 0;
        try {
            //更换签到图片
            $url = $this->gdzyz_url.'/api/mission/manage/refreshSignCode4PC.do';

            $client = new Client();

            $params = [
                'headers' => $this->_get_header(),
                'form_params' => [
                    'missionId' => $activity->missionId,
                    'mark' => 0
                ]
            ];

            $res = $client->post($url, $params);

            $data = json_decode($res->getBody()->__toString());


            if (isset($data->errcode)) {
                throw new \Exception($data->errmsg, $data->errcode);
            }
            if ($data->code == 1) {
                $code1 = 1;
                $activity->signinCode = 'http://image.izyz.org/obs-izy/'.$data->msg;
            }

            //更换签退图片
            $url = $this->gdzyz_url.'/api/mission/manage/refreshSignCode4PC.do';

            $client = new Client();

            $params = [
                'headers' => $this->_get_header(),
                'form_params' => [
                    'missionId' => $activity->missionId,
                    'mark' => 1
                ]
            ];

            $res = $client->post($url, $params);

            $data = json_decode($res->getBody()->__toString());

            if ($data->code == 1) {
                $code2 = 1;
                $activity->signoutCode = 'http://image.izyz.org/obs-izy/'.$data->msg;
            }

            if ($code1 && $code2) {
                $activity->signStartTime = date("Y-m-d H:i:s");
                $activity->signEndTime = date("Y-m-d").' 23:59:59';
                $activity->save();
            }

        } catch (\Exception $e) {
            throw new \Exception($e->getMessage(), 500);
        }
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getConfig()
    {
        $data = [];
        $configs = GdzyzConfig::select();

        foreach ($configs as $config) {
            $data[$config->configKey] = $config->configValue;
        }

        return $data;
    }

    public function updateConfig($params)
    {
        try {
            if (empty($params)) {
                return false;
            }

            foreach ($params as $value) {
                $config = GdzyzConfig::where(['configKey' => $value['configKey']])->find();

                if ($config instanceof GdzyzConfig) {
                    if (is_array($value['configValue'])) {
                        $value['configValue'] = json_encode($value['configValue'], JSON_UNESCAPED_UNICODE);
                    }
                    $config->configValue = $value['configValue'];
                    $config->save();
                }
            }

            return true;

        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }

    public function getAccessToken()
    {
        try {
            $url = $this->gdzyz_url.'/api/Log/login';

            $client = new Client();

            $params = [
                'headers' => $this->_get_header(),
                'form_params' => [
                    'mobile' => $this->config['weikeyun_account'],
                    'password' => $this->config['weikeyun_password'],
                    'loginType' => 0
                ]
            ];

            $res = $client->post($url, $params);

            $data = json_decode($res->getBody()->__toString());

            if ($data->code == 1) {
                (new ConfigService())->update('weikeyun_token', $data->data->token);
            }
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage(), 500);
        }
    }

    private function _get_header()
    {
        $headers = [
            "Accept" => "application/json, text/plain, */*",
            "Accept-Encoding" => "gzip, deflate, br",
            "Accept-Language" => "zh-CN,zh;q=0.9,en;q=0.8",
            "Content-Type" => "application/x-www-form-urlencoded; charset=UTF-8",
            "Cookie" => $this->gdzyz_token,
            "Host" => "www.gdzyz.cn",
            "Origin" => "https://www.gdzyz.cn/mission/manage/listActive.do?type=1",
            "sec-ch-ua" => '"Google Chrome";v="105", "Not)A;Brand";v="8", "Chromium";v="105"',
            "sec-ch-ua-mobile" => "?0",
            "sec-ch-ua-platform" => '"macOS"',
            "Sec-Fetch-Dest" => "empty",
            "Sec-Fetch-Mode" => "cors",
            "Sec-Fetch-Site" => "same-origin",
            "User-Agent" => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36",
        ];

        return $headers;
    }
}